package com.leenleda.ips.receiver;

import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.leenleda.ips.util.LogUtils;
import com.leenleda.ips.util.UShared;

public class KeepLiveService extends Service {

    private String tag = "KeepLiveService";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        LogUtils.e(tag, "=======onCreate======"  );
        registerBroad();
    }

    private ReceiverMsg receiverMsg;
    private TimeReceiver timeReceiver;
    private void registerBroad(){
        if (receiverMsg == null){
            UShared.putLong(Constant.DEVICE_OPEN_TIME, System.currentTimeMillis() / 1000);
            IntentFilter filter = new IntentFilter();
            filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            filter.addAction("android.intent.action.BOOT_COMPLETED");
            filter.addAction(Constant.RECEIVE_FORM_SERVICE);
            receiverMsg = new ReceiverMsg();
            registerReceiver(receiverMsg,filter);
        }
        if (timeReceiver == null){
            IntentFilter filter = new IntentFilter();
            filter.addAction(Constant.TIMER_LOOP_ACTION);
            filter.addAction(Intent.ACTION_TIME_TICK);
            filter.addAction(Constant.SWITCH_PLAY);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
            timeReceiver = new TimeReceiver();
            registerReceiver(timeReceiver,filter);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timeReceiver != null)
            unregisterReceiver(timeReceiver);
        if (receiverMsg != null)
            unregisterReceiver(receiverMsg);
    }
}
